<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
         <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['aipay:apiAccount:add']">新增</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5"></el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="postList">
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="接口上游" align="center" prop="paramsName" />
      <el-table-column label="是否代付" align="center" prop="proxyPayStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_bool_status" :value="scope.row.proxyPayStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="是否内充通道" align="center" prop="innerChannelStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_bool_status" :value="scope.row.innerChannelStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="接口域名" align="center" prop="domain" />
      <el-table-column label="通道信息" align="center" prop="channelInfo">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="formatChannel(scope.row)" placement="bottom">
            <el-button v-show="scope.row.channelInfo" type="text">查看</el-button>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-setting"
            @click="handleSetting(scope.row)"
            v-hasPermi="['aipay:apiAccount:edit']"
          >通道设置</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['aipay:apiAccount:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['aipay:apiAccount:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.limit"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" :close-on-click-modal="false" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称"/>
        </el-form-item>
        <el-form-item label="上游类型" prop="paramsId">
          <el-select v-model="form.paramsId" @change="handleSelectParams" placeholder="上游类型" size="small" :clearable="true">
            <el-option
              v-for="item in paramsList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="接口参数" prop="content" v-show="form.paramsId">
           <el-table :data="content">
             <el-table-column label="名称" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.name"
                    placeholder="请输入名称"
                    clearable
                    size="small"
                  />
                </template>
              </el-table-column>
              <el-table-column label="标识" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.number"
                    placeholder="请输入标识"
                    clearable
                    size="small"
                  />
                </template>
              </el-table-column>
              <el-table-column label="默认值" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.value"
                    placeholder="请输入默认值"
                    clearable
                    size="small"
                  />
                </template>
              </el-table-column>
            </el-table>
        </el-form-item>
        <el-form-item label="是否代付" prop="proxyPayStatus">
          <el-select v-model="form.proxyPayStatus" placeholder="是否代付" size="small" :clearable="true">
            <el-option
              v-for="dict in dict.type.sys_bool_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
          <div><el-tag type="warning">该账户是否具有代付功能。</el-tag></div>
        </el-form-item>
        <el-form-item label="是否内充通道" prop="innerChannelStatus">
          <el-select v-model="form.innerChannelStatus" placeholder="是否内充通道" size="small" :clearable="true">
            <el-option
              v-for="dict in dict.type.sys_bool_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
          <div><el-tag type="warning">该账户是否为内充通道，开启则该通道只能用于充值，一般适用于纯代付商户的充值。</el-tag></div>
        </el-form-item>
        <el-form-item label="接口域名" prop="domain">
          <el-input v-model="form.domain" placeholder="请输入接口域名"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="settingTitle" :visible.sync="openSetting" width="1000px" :close-on-click-modal="false" append-to-body>
      <el-table :data="channelInfo">
        <el-table-column label="支持" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-checkbox v-model="scope.row.checked"></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column label="接口名称" align="center" prop="name" />
        <el-table-column label="系统费率" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-input v-model="scope.row.sysFee" placeholder="请输入系统费率" clearable size="small" />
          </template>
        </el-table-column>
        <el-table-column label="上游费率" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-input v-model="scope.row.upFee" placeholder="请输入上游费率" clearable size="small" />
          </template>
        </el-table-column>
        <el-table-column label="单笔最低金额" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-input v-model="scope.row.minAmount" placeholder="请输入单笔最低金额" clearable size="small" />
          </template>
        </el-table-column>
        <el-table-column label="单笔最大金额" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-input v-model="scope.row.maxAmount" placeholder="请输入单笔最大金额" clearable size="small" />
          </template>
        </el-table-column>
        <el-table-column label="每日限额" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-input v-model="scope.row.limitAmount" placeholder="请输入每日限额" clearable size="small" />
          </template>
        </el-table-column>
        <el-table-column label="是否跳转本站" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
             <el-select v-model="scope.row.isLink" placeholder="是否跳转本站" size="small" :clearable="true">
                <el-option
                  v-for="dict in dict.type.sys_bool_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
          </template>
        </el-table-column>
        <el-table-column label="开关" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.status" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSettingForm">确 定</el-button>
        <el-button @click="cancelSettingForm">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listPaymentParamsAll } from "@/api/aipay/paymentParams";
import { listPaymentTypeAll } from "@/api/aipay/paymentType";
import { listPaymentAccount, getPaymentAccount, addPaymentAccount, updatePaymentAccount, delPaymentAccount  } from "@/api/aipay/paymentAccount";

export default {
  name: "PaymentAccount",
  dicts: ['sys_bool_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      //表格数据
      postList: [],
      paramsList: [],
      typeList: [],
      content: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openSetting: false,
      settingTitle: '',
      // 查询参数
      queryParams: {
        page: 1,
        limit: 10,
        name: undefined,
      },
      content: [],
      channelInfo: [{checked: false, id: 0, name: '', number: '', sysFee: 0, upFee: 0, minAmount: 0, maxAmount: 0, limitAmount: 0, isLink: '0', status: true}],
      // 表单参数
      form: {
        id: undefined,
        name: undefined,
        paramsId: undefined,
        paramsContent: undefined,
        proxyPayStatus: undefined,
        innerChannelStatus: undefined,
        domain: undefined,
        channelInfo: undefined
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        paramsId: [
          { required: true, message: "上游类型不能为空", trigger: "change" }
        ],
        proxyPayStatus: [
          { required: true, message: "是否代付不能为空", trigger: "change" }
        ],
        innerChannelStatus: [
          { required: true, message: "是否内充通道不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getAllPaymentParamsAll();
    this.getAllPaymentTypeAll();
    this.getList();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      listPaymentAccount(this.queryParams).then(response => {
        this.postList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getAllPaymentTypeAll(){
      listPaymentTypeAll().then(response => {
        this.typeList = response.data;
      });
    },
    getAllPaymentParamsAll(){
      listPaymentParamsAll().then(response => {
        this.paramsList = response.data;
      });
    },
    handleSelectParams(id){
      if(id){
        for(let i = 0; i < this.paramsList.length; i++){
          if(this.paramsList[i].id === id){
            if(this.paramsList[i].content){
              this.content = JSON.parse(this.paramsList[i].content);
            } else {
              this.content = [];
            }
          }
        }
      }
      
    },
    formatChannel(row){
      let info = '';
      if(row.channelInfo){
        let list = JSON.parse(row.channelInfo);
        for(let i = 0; i < list.length; i++){
          let item = list[i];
          info += `${item.name}(${item.number})【 ${item.status ? '开启' : '关闭'} 】  费率：${item.sysFee}%  上游费率：${item.upFee}%  充值金额：${item.minAmount}-${item.maxAmount} 每日限额：${item.limitAmount == '0' ? '不限' : item.limitAmount}`;
        }
      }
      return info;
    },
    handleSetting(row){
      this.reset();
      this.form.id = row.id;
      let infoList = [];
      if(row.channelInfo){
        infoList = JSON.parse(row.channelInfo);
      }
      if(this.typeList && this.typeList.length > 0){
          let list = [];
          for(let i = 0; i < this.typeList.length; i++){
            let exitsObj = null;
            if(infoList.length > 0){
              for(let j = 0; j < infoList.length; j++){
                if(parseInt(infoList[j].id) == this.typeList[i].id){
                  exitsObj = infoList[j];
                  break;
                }
              }
            }
            if(exitsObj){
              list.push(exitsObj);
            } else {
              list.push({checked: false, id: this.typeList[i].id, name: this.typeList[i].name, number: this.typeList[i].number, sysFee: 0, upFee: 0, minAmount: 0, maxAmount: 0, limitAmount: 0, isLink: 0, status: true});
            }
          }
          this.channelInfo = list;
      }
      this.settingTitle = `您正在设置:【${row.name}】所支持的通道以及费率`;
      this.openSetting = true
    },
    submitSettingForm(){
      this.form.channelInfo = "";
      let list = this.channelInfo.filter(item => item.checked);
      if(list && list.length > 0){
        this.form.channelInfo = JSON.stringify(list);
      }
      updatePaymentAccount(this.form).then(response => {
        this.msgSuccess("设置成功");
        this.openSetting = false;
        this.getList();
      });
    },
    cancelSettingForm(){
      this.openSetting = false;
      this.reset();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        paramsId: undefined,
        paramsContent: undefined,
        proxyPayStatus: undefined,
        innerChannelStatus: undefined,
        domain: undefined,
        channelInfo: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.postId)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加接口帐户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getPaymentAccount(row.id).then(response => {
        this.form = response.data;
        this.form.proxyPayStatus = this.form.proxyPayStatus + '';
        this.form.innerChannelStatus = this.form.innerChannelStatus + '';
        if(this.form.paramsContent){
          this.content = JSON.parse(this.form.paramsContent);
        } else {
          this.content = [];
        }
        this.open = true;
        this.title = "修改接口帐户";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.paramsContent = JSON.stringify(this.content);
          if (this.form.id != undefined) {
            updatePaymentAccount(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPaymentAccount(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delPaymentAccount(row.id);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    }
    
  }
};
</script>
